package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @ClassName PermissionServiceImpl
 * @Description
 * @Author Mr.Ho
 * @Date 10:12 2019/7/16
 * @Version 1.1
 **/

@Service(interfaceClass = PermissionService.class)
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    //分页查询
    @Override
    public PageResult<Permission> findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        //模糊查询需要凭借
        if(!StringUtils.isEmpty(queryPageBean.getQueryString()))
        {
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%");
        }
        //使用分页插件
        PageHelper.startPage(currentPage,queryPageBean.getPageSize());
        //紧接着查询的语句会被拦截进行分页  查询所有
        Page<Permission> page = permissionDao.findByCondition(queryPageBean.getQueryString());
        //使用pageresult包装
        PageResult<Permission> result = new PageResult<>(page.getTotal(), page.getResult());
        return result;
    }

    @Override
    public void add(Permission permission) {
        permissionDao.add(permission);
    }


    @Override
    public Permission findById(int id) {

        return permissionDao.findById(id);
    }

    @Override
    public void update(Permission permission) {
        permissionDao.update(permission);
    }

    @Override
    public void deleteById(int id) {
        int count = permissionDao.countByPermissionId(id);
        if(count>0)
        {
            throw new RuntimeException(MessageConstant.DELETE_PERMISSION_USED);
        }
        permissionDao.deleteById(id);
    }


    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }

    @Override
    public List<Integer> findPermissionIdsByRoleId(int id) {
        return permissionDao.findPermissionIdsByRoleId(id);
    }


}


